<template>
  <view class="inbound-container">
    <!-- 搜索栏及两侧按钮 -->
    <view class="search-row">
      <!-- <u-button class="icon-btn" type="success" size="mini" @click="onScanInbound"
        :custom-style="{ padding: '0 16rpx', marginRight: '10rpx' }">
        <u-icon name="scan" size="24" color="#333"></u-icon>
      </u-button> -->
      <view class="search-box-flex" @click.stop="onShowLocation">
        <u-search v-model="searchKeyword" placeholder="选择库位" :show-action="false" :clearabled="true"></u-search>
      </view>
    </view>
    <location-pop :show="showLocationPicker" @update:selectedIds="selectedLocationIds = $event"
      @close="showLocationPicker = false" @confirm="onLocationMultiConfirm" :locationList="locationList"></location-pop>

    <!-- tabs页签 -->
    <view class="tabs-section">
      <u-tabs :list="tabList" v-model:current="currentTab" @change="onTabChange" lineColor="#2979ff"
        :activeStyle="{ color: '#2979ff', fontWeight: 'bold' }" :inactiveStyle="{ color: '#666' }"></u-tabs>
    </view>

    <!-- 列表区域 -->
    <view class="list-section">
      <!-- 订单列表 -->
      <view class="order-list">
        <view class="order-item" v-for="(item, index) in orderList" :key="item.id">
          <view class="order-header">
            <view class="order-info">
              <text class="order-number">{{ item.cartons_no }}</text>
              <u-tag :text="item.task_status_name" :type="getStatusType(item.status_code)" size="mini"></u-tag>
            </view>
            <view class="order-date">
              <text class="date-text">{{ formatDate(item.scan_time) }}</text>
            </view>
          </view>

          <view class="order-content">
            <!-- <view class="supplier-info">
              <u-icon name="account" size="16" color="#666"></u-icon>
              <text class="supplier-text">{{ item.supplierName }}</text>
            </view> -->
            <!-- <view class="goods-info">
              <text class="goods-text">{{ item.goodsCount }}种商品</text>
              <text class="quantity-text">共{{ item.totalQuantity }}件</text>
            </view> -->
            <view class="box-info">
              <view class="box-meta">
                <text class="box-text">规格: {{
                  `${[item.cartons_length, item.cartons_width, item.cartons_height].filter(Boolean).join(' x ')}` ||
                  '--' }} CM</text>
                <text class="box-text">重量: {{ item.cartons_weight || '--' }} KG</text>
              </view>
            </view>
          </view>
          <view class="action-buttons">
            <u-button type="primary" size="mini" @click="onOrderClick(item)">
              上架
            </u-button>
          </view>
          <!-- <view class="order-footer">
            <view class="progress-info">
              <text class="progress-text">上架进度: {{ item.inboundQuantity }}/{{ item.totalQuantity }}</text>
              <u-line-progress :percentage="getProgressPercentage(item)" :show-text="false"
                height="6"></u-line-progress>
            </view>
          </view> -->
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-loadmore :status="loadMoreStatus" @loadmore="onLoadMore"></u-loadmore>
      </view>
      <!-- 到底了提示 -->
      <view class="no-more" v-if="!hasMore && orderList.length > 0">
        <text class="no-more-text">—— 到底了 ——</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="orderList.length === 0 && !loading">
        <u-empty text="暂无入库订单" mode="list"></u-empty>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup v-model="showFilterModal" mode="bottom" :closeable="true" :round="10">
      <view class="filter-modal">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
        </view>
        <view class="filter-content">
          <view class="filter-item">
            <text class="filter-label">订单状态</text>
            <u-radio-group v-model="filterStatus" @change="onFilterChange">
              <u-radio v-for="status in statusOptions" :key="status.value" :name="status.value"
                :label="status.label"></u-radio>
            </u-radio-group>
          </view>
          <view class="filter-item">
            <text class="filter-label">时间范围</text>
            <u-datetime-picker v-model="filterDateRange" mode="range" @confirm="onDateRangeChange"></u-datetime-picker>
          </view>
        </view>
        <view class="filter-actions">
          <u-button @click="onResetFilter">重置</u-button>
          <u-button type="primary" @click="onApplyFilter">确定</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import api from "@/api"
const INBOUND_CODE = {
  PEDDING: 110,
  IN: 120
}
import LocationPop from "../../components/LocationPop.vue"
export default {
  components: {
    LocationPop,
  },
  data() {
    return {
      // 搜索相关
      searchKeyword: '',

      // 筛选相关
      showFilterModal: false,
      filterStatus: INBOUND_CODE.PEDDING,
      filterDateRange: [],

      // 列表数据
      orderList: [],
      loading: false,
      hasMore: true,
      loadMoreStatus: 'loadmore',

      // 分页参数
      page: 1,
      pageSize: 10,

      // 统计数据
      totalCount: 0,
      pendingCount: 0,
      completedCount: 0,

      // 状态选项
      statusOptions: [
        { label: '全部', value: '' },
        { label: '待上架', value: INBOUND_CODE.PEDDING },
        { label: '已完成', value: 'completed' },
        { label: '已取消', value: 'cancelled' }
      ],

      // tabs相关
      tabList: [
        { name: '全部', value: '' },
        { name: '待上架(0)', value: INBOUND_CODE.PEDDING },
        { name: '已完成(0)', value: 'completed' }
      ],
      currentTab: 0,

      // 库位
      showLocationPicker: false,
      selectedLocationIds: [],
      locationList: [],
      current:{}
    }
  },
  onLoad() {
    this.loadOrderList()
    this.loadStatistics()
  },
  onPullDownRefresh() {
    this.refreshData()
  },
  onReachBottom() {
    if (this.hasMore && this.loadMoreStatus === 'loadmore') {
      this.onLoadMore()
    }
  },
  methods: {
    // 库位
    async onLocationMultiConfirm() {
      // 多选库位确认
      const selected = this.locationList.filter(l => this.selectedLocationIds.includes(l.guid))
      this.searchKeyword = selected.map(l => l.location_code).join(', ')
      const res = await api.inbound.getInboundList('putSale', {
        data: {
          guid: this.current.guid,
          actual_location: this.searchKeyword
        }
      });
      this.showLocationPicker = false
      uni.$u.toast("操作成功");
      this.refreshData();
    },
    async onShowLocation() {
      this.showLocationPicker = true;
      this.locationList = [];
      const res = await api.wms.locationApi("locationList", {
        data: {
          guid_warehouse: "dc95299b-f8ff-4e0f-8481-60d32e1da83a"
        }
      })
      this.locationList = res.data.data;
    },
    // 加载订单列表
    async loadOrderList(isLoadMore = false) {
      if (this.loading) return

      this.loading = true
      if (!isLoadMore) {
        this.page = 1
        this.orderList = []
      }

      try {
        // 模拟API调用
        const params = {
          page: {
            current: this.page,
            size: this.pageSize,
          },
          data: {
            task_status: 'TASK_PENDING',
            status_code: this.filterStatus
          }
        }

        // 模拟数据
        const res = await api.inbound.getInboundList('selectPutAwayTask', params)
        this.orderList = this.orderList.concat(res.data.data);

        this.hasMore = Boolean(res.data.data?.length);
        this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore'

        if (isLoadMore) {
          this.page++
        }

      } catch (error) {
        console.error('加载订单列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        // 模拟统计数据
        this.totalCount = 156
        this.pendingCount = 23
        this.completedCount = 133
        // 更新tab数量
        this.tabList = [
          { name: `待上架(${this.pendingCount})`, value: INBOUND_CODE.PEDDING },
          { name: `已完成(${this.completedCount})`, value: 'completed' }
        ]
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },

    // 搜索
    onSearch() {
      this.loadOrderList()
    },

    // 清除搜索
    onClear() {
      this.searchKeyword = ''
      this.loadOrderList()
    },

    // 刷新数据
    onRefresh() {
      this.refreshData()
    },

    // 刷新数据
    refreshData() {
      this.loadOrderList()
      this.loadStatistics()
    },

    // 加载更多
    onLoadMore() {
      if (this.hasMore && !this.loading) {
        this.loadMoreStatus = 'loading'
        this.loadOrderList(true)
      }
    },

    // 筛选变化
    onFilterChange() {
      // 筛选条件变化时的处理
    },

    // 日期范围变化
    onDateRangeChange(e) {
      this.filterDateRange = e
    },

    // 重置筛选
    onResetFilter() {
      this.filterStatus = ''
      this.filterDateRange = []
    },

    // 应用筛选
    onApplyFilter() {
      this.showFilterModal = false
      this.loadOrderList()
    },

    // 新增入库
    onAddInbound() {
      uni.navigateTo({
        url: '/pages/inbound/add/add'
      })
    },

    // 扫一扫入库
    onScanInbound() {
      uni.scanCode({
        success: (res) => {
          console.log('扫码结果:', res.result)
          // 处理扫码结果，可以跳转到相应的页面
          uni.showToast({
            title: '扫码成功',
            icon: 'success'
          })
          // 这里可以根据扫码结果跳转到相应的页面
          // uni.navigateTo({
          // 	url: `/pages/inbound/scan-result/scan-result?code=${res.result}`
          // })
        },
        fail: (err) => {
          console.log('扫码失败:', err)
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },

    // 订单点击
    async onOrderClick(item) {
      this.current = item;
      this.onShowLocation();
      // if (!this.searchKeyword) {
      //   uni.showToast({
      //     title: "请选择库位",
      //     icon: "error"
      //   })
      //   return;
      // }
      // const res = await api.inbound.getInboundList('putSale', {
      //   data: {
      //     guid: item.guid,
      //     actual_location: this.searchKeyword
      //   }
      // })
      // this.searchKeyword = "";
      // uni.showToast("操作成功");
      // this.refreshData();
      // uni.navigateTo({
      //   url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
      // })
    },

    // 开始入库
    onStartInbound(item) {
      uni.navigateTo({
        url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
      })
    },

    // 继续入库
    onContinueInbound(item) {
      uni.navigateTo({
        url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
      })
    },

    // 查看详情
    onViewDetail(item) {
      uni.navigateTo({
        url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
      })
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        [INBOUND_CODE.PEDDING]: '待入库',
        'processing': '入库中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        [INBOUND_CODE.PEDDING]: 'warning',
        'processing': 'primary',
        'completed': 'success',
        'cancelled': 'error'
      }
      return typeMap[status] || 'info'
    },

    // 获取进度百分比
    getProgressPercentage(item) {
      if (item.totalQuantity === 0) return 0
      return Math.round((item.inboundQuantity / item.totalQuantity) * 100)
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },

    onTabChange(index) {
      this.currentTab = index;
      this.filterStatus = this.tabList[index].value;
      this.loadOrderList();
    },
  }
}
</script>

<style lang="scss" scoped>
.inbound-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20rpx;
}

// 搜索区域
.search-row {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20rpx 20rpx 0 20rpx;

  .search-box-flex {
    flex: 1;
  }

  .icon-btn {
    border-radius: 50%;
    padding: 0 !important;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
  }
}

// tabs页签
.tabs-section {
  background: #fff;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
}

// 列表区域
.list-section {
  background-color: #ffffff;
  margin: 0 20rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .order-list {
    .order-item {
      background-color: #f8f9fa;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 30rpx;
      border: 1rpx solid #e9ecef;

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 25rpx;

        .order-info {
          display: flex;
          align-items: center;

          .order-number {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-right: 25rpx;
          }
        }

        .order-date {
          .date-text {
            font-size: 26rpx;
            color: #999999;
          }
        }
      }

      .order-content {
        margin-bottom: 25rpx;

        .supplier-info {
          display: flex;
          align-items: center;
          margin-bottom: 15rpx;

          .supplier-text {
            font-size: 30rpx;
            color: #666666;
            margin-left: 15rpx;
          }
        }

        .goods-info {
          display: flex;
          justify-content: space-between;

          .goods-text,
          .quantity-text {
            font-size: 26rpx;
            color: #666666;
          }
        }

        .box-info {
          display: flex;
          align-items: flex-start;
          margin-top: 12rpx;
          margin-bottom: 4rpx;

          .box-icon {
            margin-top: 2rpx;
          }

          .box-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 24rpx;
          }

          .box-text {
            font-size: 24rpx;
            color: #888;
            line-height: 36rpx;
          }
        }
      }

      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .progress-info {
          flex: 1;
          margin-right: 30rpx;

          .progress-text {
            font-size: 26rpx;
            color: #666666;
            margin-bottom: 15rpx;
            display: block;
          }
        }

        .action-buttons {
          display: flex;
          gap: 15rpx;

          ::v-deep .u-button {
            min-width: 120rpx;
            height: 60rpx;
            font-size: 26rpx;
          }
        }
      }
    }
  }
}

// 加载更多
.load-more {
  margin-top: 40rpx;
}

// 空状态
.empty-state {
  margin-top: 120rpx;
}

// 筛选弹窗
.filter-modal {
  padding: 50rpx 40rpx;

  .filter-header {
    margin-bottom: 50rpx;

    .filter-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
  }

  .filter-content {
    .filter-item {
      margin-bottom: 50rpx;

      .filter-label {
        font-size: 32rpx;
        color: #333333;
        margin-bottom: 25rpx;
        display: block;
      }
    }
  }

  .filter-actions {
    display: flex;
    gap: 25rpx;
    margin-top: 50rpx;

    ::v-deep .u-button {
      flex: 1;
      height: 80rpx;
      font-size: 30rpx;
    }
  }
}

// 适配App端的特殊样式
/* #ifdef APP-PLUS */
.search-row {
  padding: 40rpx 20rpx;
}

.stats-section {
  padding: 50rpx 30rpx;
}

.list-section {
  padding: 50rpx 30rpx;
}

.order-list .order-item {
  padding: 35rpx;
}

.filter-modal {
  padding: 60rpx 40rpx;
}

/* #endif */

// 适配不同屏幕尺寸
@media screen and (max-width: 750rpx) {
  .stats-section {
    padding: 30rpx 20rpx;

    .stats-item .stats-number {
      font-size: 40rpx;
    }
  }

  .list-section {
    padding: 30rpx 20rpx;
  }

  .order-list .order-item {
    padding: 25rpx;
  }
}

.no-more {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin: 32rpx 0 0 0;
}

.no-more-text {
  padding: 0 24rpx;
  background: #f5f5f5;
  border-radius: 16rpx;
}
</style>